package com.finance.system.support.rpc.netty;

import com.finance.system.support.rpc.netty.msg.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IDEA
 *
 * @author: 董文辉
 * Date: 2018/1/3
 * Time: 10:35
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<BaseMsg> {
    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    /**
     * 处理从客户端发送过来的消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
        if (MsgType.LOGIN.equals(msg.getType())) {
            LoginMsg loginMsg = (LoginMsg) msg;
            if (NettyContextChannelMap.get(loginMsg.getPhoneNum()) == null) {
                // 登录成功,把channel存到服务端的map中
                NettyContextChannelMap.add(loginMsg.getPhoneNum(), (SocketChannel) ctx.channel());
                logger.info("client" + loginMsg.getPhoneNum() + " 登录成功");
            }
        } else {
            if (NettyContextChannelMap.get(msg.getPhoneNum()) == null) {
                // 说明未登录，或者连接断了，服务器向客户端发起登录请求，让客户端重新登录
                LoginMsg loginMsg = new LoginMsg();
                ctx.channel().writeAndFlush(loginMsg);
            }
        }
        switch (msg.getType()) {
            case PING:
                PingMsg pingMsg = (PingMsg) msg;
                PingMsg replyPing = new PingMsg();
                NettyContextChannelMap.get(pingMsg.getPhoneNum()).writeAndFlush(replyPing);
                logger.info("收到PING类型");
                break;
            case LOGIN:
                break;
            case PUSH:
                PushMsg pushMsg = (PushMsg) msg;
                logger.info("phoneNum = " + pushMsg.getPhoneNum() + ", content = " + pushMsg.getContent());
                break;
            default:
                logger.info("default。。");
                break;
        }
    }
}
